package LexPortal.DaoImpl;

import java.sql.*;

public class SqliteHelper {

	public static int ExecuteNonQuery(String filePath, String sql) {
		return ExecuteNonQuery(filePath, sql, null);
	}

	public static int ExecuteNonQuery(String filePath, String sql,
			String[] parameters) {
		int retCount = -1;
		Connection conn = PrepareSqliteConn(filePath);
		try {
			if (conn != null) {
				if (parameters == null || parameters.length == 0) {
					Statement stat = conn.createStatement();
					retCount = stat.executeUpdate(sql);
				} else {
					PreparedStatement prep = conn.prepareStatement(sql);
					int index = 1;
					for (String param : parameters) {
						prep.setString(index++, param);
					}
					retCount = prep.executeUpdate();
				}
			}
		} catch (SQLException ex) {
			System.out.println("SQLException: " + ex.getMessage());
			System.out.println("SQLState: " + ex.getSQLState());
			System.out.println("VendorError: " + ex.getErrorCode());
		}

		return retCount;
	}

	public static ResultSet ExecuteResultSet(String filePath, String sql) {
		return ExecuteResultSet(filePath, sql, null);
	}

	public static ResultSet ExecuteResultSet(String filePath, String sql,
			String[] parameters) {
		ResultSet rs = null;
		Connection conn = PrepareSqliteConn(filePath);

		try {
			if (conn != null) {
				if (parameters == null || parameters.length == 0) {
					Statement stat = conn.createStatement();
					rs = stat.executeQuery(sql);
				} else {
					PreparedStatement prep = conn.prepareStatement(sql);
					int index = 1;
					for (String param : parameters) {
						prep.setString(index++, param);
					}
					rs = prep.executeQuery();
				}
			}
		} catch (SQLException ex) {
			System.out.println("SQLException: " + ex.getMessage());
			System.out.println("SQLState: " + ex.getSQLState());
			System.out.println("VendorError: " + ex.getErrorCode());
		}

		return rs;
	}

	private static Connection PrepareSqliteConn(String filePath) {
		Connection conn = null;
		try {
			Class.forName("org.sqlite.JDBC");
			conn = DriverManager.getConnection("jdbc:sqlite:" + filePath);
		} catch (ClassNotFoundException ex) {
			System.out.println("ClassNotFoundException: " + ex.getMessage());
		} catch (SQLException ex) {
			// handle any errors
			System.out.println("SQLException: " + ex.getMessage());
			System.out.println("SQLState: " + ex.getSQLState());
			System.out.println("VendorError: " + ex.getErrorCode());
		}
		return conn;
	}
}
